package com.chkj.fbook.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.chkj.fbook.system.service.MenuService;
import com.chkj.fbook.system.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chkj.fbook.common.annotation.Log;
import com.chkj.fbook.common.controller.BaseController;
import com.chkj.fbook.common.domain.FileDO;
import com.chkj.fbook.common.domain.Tree;
import com.chkj.fbook.common.service.FileService;
import com.chkj.fbook.common.utils.BuildTree;
import com.chkj.fbook.common.utils.MD5Utils;
import com.chkj.fbook.common.utils.R;
import com.chkj.fbook.common.utils.SessionPermission;
import com.chkj.fbook.common.utils.SessionUtils;
import com.chkj.fbook.system.domain.MenuDO;
import com.chkj.fbook.system.domain.UserDO;

import io.swagger.annotations.ApiParam;

@Controller
public class LoginController extends BaseController {
	
    // 登录页
 	private static final String LOGIN_PATH = "login";

    @Autowired
    MenuService menuService;
    @Autowired
    FileService fileService;
    @Autowired
    UserService userService;
    
    @GetMapping({"/", ""})
	public String welcome(Model model) {

    	return LOGIN_PATH;
    }

    @Log("请求访问主页")
    @GetMapping({"/index"})
	public String index(Model model, HttpServletRequest request, HttpServletResponse response) {

		UserDO sessionUser = SessionUtils.getSessionUser(request);
		if (sessionUser == null) {
			return LOGIN_PATH;
		}

    	SessionPermission sessionPermission = SessionUtils.getSessionPermission(request,"ssoServer");

    	List<MenuDO>  mlist = sessionPermission.getMenuList();
    	
    	List<Tree<MenuDO>> trees = new ArrayList<Tree<MenuDO>>();
    	String curSysId="ssoServer";
		for (MenuDO sysMenuDO : mlist) {
			
			//如果是系统目录，则去掉
			
			if("ssoServer".equals(sysMenuDO.getPerms())) {
				curSysId = sysMenuDO.getMenuId();
				continue;
			}
			
			Tree<MenuDO> tree = new Tree<MenuDO>();
			tree.setId(sysMenuDO.getMenuId().toString());
			tree.setParentId(sysMenuDO.getParentId().toString());
			tree.setText(sysMenuDO.getName());
			Map<String, Object> attributes = new HashMap<>(16);
			attributes.put("url", sysMenuDO.getUrl());
			attributes.put("icon", sysMenuDO.getIcon());
			tree.setAttributes(attributes);
			trees.add(tree);
		}
		// 默认顶级菜单为０，根据数据库实际情况调整
		List<Tree<MenuDO>> menus = BuildTree.buildList(trees, curSysId);
        model.addAttribute("menus", menus);
        model.addAttribute("name", getUser().getName());
        FileDO fileDO = fileService.get(getUser().getPicId());
        if (fileDO != null && fileDO.getUrl() != null) {
            if (fileService.isExist(fileDO.getUrl())) {
                model.addAttribute("picUrl", fileDO.getUrl());
            } else {
                model.addAttribute("picUrl", "/img/logo_h.png");
            }
        } else {
            model.addAttribute("picUrl", "/img/logo_h.png");
        }
        model.addAttribute("username", getUser().getUsername());
        return "index_v1";
    }

    @GetMapping("/login")
	public String login(Model model,String backUrl, HttpServletRequest request) {
		return LOGIN_PATH;
    }

    @Log("登录")
    @PostMapping("/login")
    @ResponseBody
	public R ajaxLogin(String username, String password, HttpServletRequest request, HttpServletResponse response) {

        try {
        	
        	if(StringUtils.isBlank(username)) {
        		return R.error(-1, "账号不能为空");
        	}
        	if(StringUtils.isBlank(password)) {
        		return R.error(-1, "密码不能为空");
        	}
        	
        	//防止重复登陆
        	
        	UserDO user = userService.getByUserName(username);
        	// 账号不存在
    		if (user == null) {
    			return R.error(-1, "账号或密码不正确");
    		}
    		
    		password = MD5Utils.encryptPassword(MD5Utils.md5(password));

    		// 密码错误
    		if (!password.equals(user.getPassword())) {
    			return R.error(-1, "账号或密码不正确");
    		}

    		// 账号锁定
    		if (user.getStatus() == 0) {
    			return R.error(-1, "账号已被锁定,请联系管理员");
    		}
    		
    		//登录成功：当前用户放入session
			SessionUtils.setSessionUser(request, user);
			//设置权限
			List<MenuDO> userPermission = menuService.findListById("ssoServer", user.getUserId());
			invokePermissionInSession(request,userPermission,"ssoServer");
    		
			return R.ok();
            
        } catch (Exception e) {
        	return R.error("系统异常,请联系管理员");
        }
    }
    
    /**
	 * 保存权限信息
	 */
	public SessionPermission invokePermissionInSession(HttpServletRequest request, List<MenuDO> dbList , String appCode) {

		List<MenuDO> menuList = new ArrayList<MenuDO>();
		Set<String> operateSet = new HashSet<String>();
		for (MenuDO menu : dbList) {
			if (0 == menu.getType() || 1 == menu.getType()) {
				// 菜单和目录 
				menuList.add(menu);
			}
			if (!StringUtils.isEmpty(menu.getPerms())) {
				operateSet.add(menu.getPerms());
			}
		}

		SessionPermission sessionPermission = new SessionPermission(); // 设置登录用户菜单列表
		sessionPermission.setMenuList(menuList);

		// 保存登录用户权限列表
		sessionPermission.setPermissionSet(operateSet);
		SessionUtils.setSessionPermission(request, appCode, sessionPermission);
		return sessionPermission;

	}
    
    @GetMapping("/logout")
    public String logout(@ApiParam(value = "返回链接") String backUrl, HttpServletRequest request) {
    	SessionUtils.invalidate(request);
		return "redirect:"+LOGIN_PATH;
	}

    @GetMapping("/main")
	public String main() {
        return "mainBench";
    }
    
}
